package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UpkeepAuditServiceImpl implements UpkeepAuditService {

    @Autowired
    private UpkeepAuditDao upkeepAuditDao;

    @Autowired
    private UpkeepDao upkeepDao;

    @Autowired
    private PcbaLineDao pcbaLineDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Autowired
    private UpkeepHistoryDao upkeepHistoryDao;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Autowired
    private UserDao userDao;

    @Value("${personal.config.env}")
    private String env;

    @Autowired
    private ThirdApiService thirdApiService;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "保养计划";

    @Override
    public Result addUpkeepAudit(UpkeepAudit upkeepAudit) {
        try {
            String assetNumber = upkeepAudit.getAssetNumber();
            Integer upkeepType = upkeepAudit.getUpkeepType();
            if (assetNumber == null || "".equals(assetNumber)) {
                return ResultUtil.error(500, "缺少参数assetNumber", "Miss Param assetNumber", null);
            }
            if (upkeepType == null || "".equals(upkeepType.toString())) {
                return ResultUtil.error(500, "缺少参数upkeepType", "Miss Param upkeepType", null);
            }

            String userId = UserHeaderHolder.getUserId();

            UpkeepAudit u = upkeepAuditDao.getUpkeepAuditByAssetNumberAndUpkeepType(assetNumber, upkeepType);
            if (u != null) {
                // update
                UpkeepAudit updateUpkeepAudit = new UpkeepAudit();
                updateUpkeepAudit.setIsDelete(2);
                updateUpkeepAudit.setUpdateTime(new Date());
                updateUpkeepAudit.setUpkeepStatus(4);
                updateUpkeepAudit.setUpkeepId(u.getUpkeepId());
                upkeepAuditDao.updateUpkeepAudit(updateUpkeepAudit);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(u), JSONObject.toJSONString(upkeepAudit)));

                return ResultUtil.success(null);
            } else {
                // insert
                upkeepAudit.setCreateTime(new Date());
                upkeepAudit.setIsDelete(2);
                upkeepAudit.setUpkeepStatus(4);
                PcbaDevice pcbaDevice = pcbaDeviceDao.getByAssetNumber(assetNumber);
                if (pcbaDevice != null) {
                    upkeepAudit.setPcbaDeviceId(pcbaDevice.getPcbaDeviceId());
                    upkeepAuditDao.addUpkeepAudit(upkeepAudit);

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(upkeepAudit)));

                    return ResultUtil.success(null);
                } else {
                    return ResultUtil.error(500, "未找到pcbaDevice", "Not Found pcbaDevice", null);
                }
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    @Transactional(transactionManager = "MysqlTransactionManager1")
    public Result auditUpkeepAudit(String notes, Integer upkeepId, Integer upkeepStatus) {
        Integer pcbaDeviceId = null;
        try {
            if (upkeepId == null || "".equals(upkeepId.toString())) {
                return ResultUtil.error(500, "缺少参数upkeepId", "Miss Param upkeepId", null);
            }
            if (upkeepStatus == null || "".equals(upkeepStatus.toString())) {
                return ResultUtil.error(500, "缺少参数upkeepStatus", "Miss Param upkeepStatus", null);
            }
            if (upkeepStatus != 1 && upkeepStatus != 2) {
                return ResultUtil.error(500, "upkeepStatus参数错误", "Error Param upkeepStatus", null);
            }

            String userId = UserHeaderHolder.getUserId();

            // 1.审核 通过或者不通过
            UpkeepAudit updateUpkeepAudit = new UpkeepAudit();
            updateUpkeepAudit.setUpdateTime(new Date());
            updateUpkeepAudit.setNotes(notes);
            updateUpkeepAudit.setUpkeepStatus(upkeepStatus);
            updateUpkeepAudit.setUpkeepId(upkeepId);
            upkeepAuditDao.updateUpkeepAudit(updateUpkeepAudit);

            // 2.如果审核通过，将该条写入 upkeep表【需判断原先有没有，有的话更新，没有的话新增,可以执行先删除再新增】
            UpkeepAudit upkeepAudit = upkeepAuditDao.getById(upkeepId);
            if (upkeepAudit != null) {
                Integer upkeepType = upkeepAudit.getUpkeepType();
                String assetNumber = upkeepAudit.getAssetNumber();

                PcbaDevice byAssetNumber = pcbaDeviceDao.getByAssetNumber(assetNumber);
                if (byAssetNumber != null) {
                    pcbaDeviceId = byAssetNumber.getPcbaDeviceId();
                }

                if (upkeepStatus == 1) {
                    Integer isDelete = upkeepAudit.getIsDelete();
                    if (isDelete == 1) {
                        //直接删除
                        upkeepDao.deleteUpkeepByAssetNumberAndUpkeepType(assetNumber, upkeepType);
                    } else {
                        //删除后再新增
                        upkeepDao.deleteUpkeepByAssetNumberAndUpkeepType(assetNumber, upkeepType);

                        Upkeep addUpkeep = new Upkeep();
                        addUpkeep.setAuditId(upkeepAudit.getAuditId());
                        addUpkeep.setVersion(upkeepAudit.getVersion());
                        addUpkeep.setContactMethod(upkeepAudit.getContactMethod());
                        addUpkeep.setOwnerId(upkeepAudit.getOwnerId());
                        addUpkeep.setFirstUpkeepTime(upkeepAudit.getFirstUpkeepTime());
                        addUpkeep.setCreateTime(new Date());
                        addUpkeep.setPcbaDeviceId(upkeepAudit.getPcbaDeviceId());
                        addUpkeep.setAssetNumber(assetNumber);
                        addUpkeep.setUpkeepType(upkeepType);
                        upkeepDao.addUpkeep(addUpkeep);
                    }
                }

                // 审核通过后将保养历史 is_current改为2

                UpkeepHistory updateUpkeepHistory = new UpkeepHistory();
                updateUpkeepHistory.setIsCurrent(2);
                updateUpkeepHistory.setAssetNumber(assetNumber);
                updateUpkeepHistory.setUpkeepType(upkeepType);
                updateUpkeepHistory.setUpdateTime(new Date());
                upkeepHistoryDao.updateUpkeepHistoryByAssetNumberAndUpkeepType(updateUpkeepHistory);

            } else {
                return ResultUtil.error(500, "未找到upkeepAudit", "Not Found upkeepAudit", null);
            }
            // 3.如果审核不通过
            UpkeepAudit upkeepAudit2 = upkeepAuditDao.getById(upkeepId);
            if (upkeepAudit2 != null) {
                if (upkeepStatus == 2) {
                    String assetNumber = upkeepAudit2.getAssetNumber();
                    Integer upkeepType = upkeepAudit2.getUpkeepType();
                    Integer isDelete = upkeepAudit2.getIsDelete();
                    if (isDelete == 1) {
                        // 假删标志 改为3
                        upkeepAudit2.setIsDelete(3);
                        upkeepAudit2.setAssetNumber(assetNumber);
                        upkeepAudit2.setUpkeepId(upkeepId);
                        upkeepAuditDao.updateUpkeepAudit(upkeepAudit);
                    }
                }
            } else {
                return ResultUtil.error(500, "未找到upkeepAudit", "Not Found upkeepAudit", null);
            }

            // 发送邮件通知
            try {
                List<User> userList = new ArrayList<>();
                if (pcbaDeviceId != null) {
                    PcbaDevice pcbaDevice = pcbaDeviceDao.getById(pcbaDeviceId);
                    if (pcbaDevice != null) {
                        Integer pcbaLineId = pcbaDevice.getPcbaLineId();
                        if (pcbaLineId != null) {
                            PcbaLine pcbaLine = pcbaLineDao.getPcbaLineById(pcbaLineId);
                            if (pcbaLine != null) {
                                PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaLine.getPcbaCompanyId());
                                if (pcbaCompany != null) {
                                    String emailOwners3 = pcbaCompany.getEmailOwners3();
                                    if (emailOwners3 != null && !"".equals(emailOwners3)) {
                                        String[] split = emailOwners3.split(",");
                                        for (String s : split) {
                                            if (s.contains("/")) {
                                                String[] strings = s.split("\\/");
                                                if (strings.length == 2) {
                                                    String domainAccount = strings[1];
                                                    if (domainAccount != null && !"".equals(domainAccount)) {
                                                        User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                        if (u != null) {
                                                            userList.add(u);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                List<MailAddress> mailAddressList = new ArrayList<>();
                for (User user : userList) {
                    if(user.getEmail().contains(",")){
                        String[] emailsArr = user.getEmail().split(",");
                        for (String email : emailsArr) {
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(email);
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }else{
                        MailAddress mailAddress = new MailAddress();
                        mailAddress.setMailAddress(user.getEmail());
                        mailAddress.setType(0);
                        mailAddressList.add(mailAddress);
                    }
                }
                if (mailAddressList.size() > 0) {
                    if (upkeepStatus == 1) {
                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_UPKEEP_TITLE_OK, DB1EmailTemplates.DEVICE_UPKEEP_MAIL_CONTENT_TITLE_OK,
                                DB1EmailTemplates.DEVICE_UPKEEP_MAIL_CONTENT_OK, "10086", mailAddressList, null, null, null, null, 2, null);
                        if (result.getCode() == 200) {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("设备维护保养计划审核结果邮件,发送成功");
                        } else {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("设备维护保养计划审核结果邮件,发送失败:" + result.getMsgCn());
                        }
                    } else if (upkeepStatus == 2) {
                        Result result = thirdApiService.sendMail("", DB1EmailTemplates.DEVICE_UPKEEP_TITLE_NO, DB1EmailTemplates.DEVICE_UPKEEP_MAIL_CONTENT_TITLE_NO,
                                DB1EmailTemplates.DEVICE_UPKEEP_MAIL_CONTENT_NO, "10086", mailAddressList, null, null, null, null, 2, null);
                        if (result.getCode() == 200) {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("设备维护保养计划审核结果邮件,发送成功");
                        } else {
                            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                            System.out.println("设备维护保养计划审核结果邮件,发送失败:" + result.getMsgCn());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                System.out.println("设备维护保养计划审核结果邮件发送失败");
            }

            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        } finally {
            // 更新计划后需刷新一遍
            coreAlgorithmService.refreshDeviceUpkeepStatus(pcbaDeviceId);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result deleteUpkeepAudit(Integer upkeepId) {
        try {
            if (upkeepId == null || "".equals(upkeepId.toString())) {
                return ResultUtil.error(500, "缺少参数upkeepId", "Miss Param upkeepId", null);
            }

            String userId = UserHeaderHolder.getUserId();

            UpkeepAudit oldUpkeepAudit = upkeepAuditDao.getById(upkeepId);
            UpkeepAudit upkeepAudit = oldUpkeepAudit;
            // 假删除保养计划
            upkeepAudit.setIsDelete(1);
            upkeepAudit.setUpkeepStatus(3);
            upkeepAudit.setUpkeepId(upkeepId);
            upkeepAuditDao.updateUpkeepAudit(upkeepAudit);

            // 操作日志
            operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldUpkeepAudit), JSONObject.toJSONString(upkeepAudit)));

            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Boolean updateUpkeepAudit(UpkeepAudit upkeepAudit) throws Exception {

        String userId = UserHeaderHolder.getUserId();
        UpkeepAudit oldUpkeepAudit = upkeepAuditDao.getById(upkeepAudit.getUpkeepId());

        upkeepAudit.setUpdateTime(new Date());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = format.parse(upkeepAudit.getFirstUpkeepTimeStr());
        upkeepAudit.setFirstUpkeepTime(time);
        upkeepAudit.setIsDelete(2);
        upkeepAudit.setUpkeepStatus(3);
        upkeepAudit.setSubmitter(Integer.parseInt(userId));

        // 操作日志
        operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldUpkeepAudit), JSONObject.toJSONString(upkeepAudit)));

        return upkeepAuditDao.updateUpkeepAudit(upkeepAudit) > 0;
    }

    @Override
    public List<UpkeepAudit> getUpkeepAuditByAssetNumber(String assetNumber, String isDeleteStr) {
        List<Integer> isDeleteList = new ArrayList<>();
        if (isDeleteStr != null && !"".equals(isDeleteStr)) {
            for (String s : isDeleteStr.split(",")) {
                isDeleteList.add(Integer.parseInt(s));
            }
        }
        return upkeepAuditDao.getUpkeepAuditByDeviceId(assetNumber, null, isDeleteList);
    }

    @Override
    public UpkeepAudit getById(Integer upkeepId) {
        return upkeepAuditDao.getById(upkeepId);
    }
}
